import { defineStore } from 'pinia';
import { ref, onMounted, reactive } from 'vue';
import { ElMessage as Message } from 'element-plus';
import screenfull from 'screenfull';
import * as Cesium from 'cesium';
import { debounce } from 'lodash';
import { Img, Img1, ADMIN_S } from '@/components/cesium/map.config';
import { useSiteInfoStore } from '@/store/modules/earlyWarning/useSiteInfoStore';
import { usePipelineInfoStore } from '@/store/modules/earlyWarning/pipelineInfo';
import { useThirdPartyRiskStore } from '@/store/modules/earlyWarning/useThirdPartyRiskStore';
import { useRescueForcesStore } from '@/store/modules/earlyWarning/useRescueForcesStore';
import { useMonitoringEquipmentStore } from '@/store/modules/earlyWarning/useMonitoringEquipmentStore';
import { useTopStore } from '@/store/modules/earlyWarning/useTopStore';
import { useDeviceAlarmsStore } from '@/store/modules/earlyWarning/useDeviceAlarmsStore';
import { useAlarmTypeStore } from '@/store/modules/earlyWarning/useAlarmTypeStore';
import { useIncidentDispositionStore } from '@/store/modules/earlyWarning/useIncidentDispositionStore';
import { useAlertOverviewStore } from '@/store/modules/earlyWarning/useAlertOverviewStore';
import { useCesiumPoints } from '@/hooks/useCesiumPoints';
import { getLargeResources } from '@/api/gasTree';
import { useGasSearchStore } from '@/store/modules/earlyWarning/useGasSearchStore';
import { MonitorTypeLabelMap } from '@/enums/MonitorTypeEnum';
import ComponentTitles from '@/constants/components/componentsTitle';

// 定义 svgList 的类型
interface SvgItem {
  name: string;
  type: string;
  url: string; // 添加 url 属性
  tooltip: string;
}

export const useAtlasStore = defineStore('atlas', () => {
  const retract = ref(true); // 是否收起两侧
  const layerShow = ref<boolean>(false); // 是否显示图层
  const baseMapStatus = ref<boolean>(true);
  const searchFlag = ref<boolean>(false);
  const svgMap = {
    search: { on: 'search', off: 'search' },
    home: '功能list-1',
    add: '功能list-2',
    minus: '功能list-3',
    fullScreen: { on: '功能list-4', off: '功能list-4-off' },
    retract: '功能list-6',
    layer: { on: '功能list', off: '功能list-off' },
    clear: 'clear'
  };

  // 初始化时为每个对象添加 url 属性
  const svgList = ref<SvgItem[]>([
    { name: 'widget-image', tooltip: '搜索', type: 'search', url: '' },
    { name: 'widget-image', tooltip: '初始化视角', type: 'home', url: '' },
    { name: 'widget-image', tooltip: '放大视角', type: 'add', url: '' },
    { name: 'widget-image', tooltip: '缩小视角', type: 'minus', url: '' },
    { name: 'widget-image', tooltip: '全屏', type: 'fullScreen', url: '' },
    { name: 'widget-image', tooltip: '收起', type: 'retract', url: '' },
    { name: 'widget-image', tooltip: '设备图层', type: 'layer', url: '' },
    { name: 'widget-image', tooltip: '清除', type: 'clear', url: '' }
  ]);

  const updateSvgUrl = () => {
    svgList.value.forEach((item) => {
      if (typeof svgMap[item.type] === 'object') {
        item.url = layerShow.value ? svgMap[item.type].on : svgMap[item.type].off;
      } else {
        item.url = svgMap[item.type];
      }
    });
  };

  const actions = {
    layer: () => {
      layerShow.value = !layerShow.value;
      svgList.value.find((item) => item.type === 'layer').url = layerShow.value ? svgMap.layer.on : svgMap.layer.off;
    },
    home: () => {
      window.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(117.140035075, 36.798747059, 400000)
      });
    },
    add: () => {
      const height = Cesium.Cartographic.fromCartesian(window.viewer.camera.position).height;
      if (height < 1100) {
        // Message({ message: '不能再放大了', type: 'warning' });
        return;
      }
      window.viewer.camera.zoomIn();
    },
    minus: () => {
      const height = Cesium.Cartographic.fromCartesian(window.viewer.camera.position).height;
      if (height > 400000) {
        // Message({ message: '不能在缩小了', type: 'warning' });
        return;
      }
      window.viewer.camera.zoomOut();
    },
    fullScreen: () => {
      if (!screenfull.isEnabled) {
        Message({ message: '你的浏览器不支持全屏', type: 'warning' });
        return false;
      }
      screenfull.toggle();
      svgList.value.find((item) => item.type === 'fullScreen')!.url = screenfull.isFullscreen ? svgMap.fullScreen.off : svgMap.fullScreen.on;
    },
    clear: () => {
      useSiteInfoStore().initSiteModule();
      usePipelineInfoStore().initPipelineInfoModule();
      useThirdPartyRiskStore().initThirdPartyRisk();
      useRescueForcesStore().initRescueForces();
      useMonitoringEquipmentStore().initClearAllPoints();
      useTopStore().initClearPoint();
      useDeviceAlarmsStore().initClearPoints();
      useAlarmTypeStore().initClearPoints();
      useIncidentDispositionStore().initClearPoints();
      useAlertOverviewStore().initClearPoints();
      useGasSearchStore().initPoints();
      initClearPoints();
      clearPointDialog();
    },
    retract: () => {
      retract.value = !retract.value;
    },
    search: () => {
      searchFlag.value = !searchFlag.value;
    }
  };

  const atlasChange = (type: string) => {
    const action = actions[type];
    if (action) {
      action();
    } else {
      Message({ message: '无效的操作类型', type: 'warning' });
    }
  };

  const screenChange = () => {
    const handleResize = debounce(() => {
      retract.value = !retract.value;
    }, 500);

    window.addEventListener('resize', handleResize);
  };

  const addImagery = () => {
    window.viewer.imageryLayers.removeAll();
    if (baseMapStatus.value) {
      // 天地图影像
      window.viewer.imageryLayers.addImageryProvider(Img);
      // 天地图影像注记
      window.viewer.imageryLayers.addImageryProvider(Img1);
    } else {
      window.viewer.imageryLayers.addImageryProvider(ADMIN_S);
    }
  };
  const treeRef = ref();
  const treeData = ref([]);
  const dataSource = reactive<Record<string, any[]>>({});
  const { addPoint, clearAllPoints } = useCesiumPoints();
  const getList = async () => {
    const { data } = await getLargeResources();
    treeData.value = [data];
  };
  const handleNodeClick = (node: { name: string; data?: any[] }, checked: boolean) => {
    // 如果节点没有数据，直接返回
    if (!node.data || node.data.length === 0) {
      return;
    }

    // 如果节点已经在数据源中，说明是取消选中
    if (dataSource[node.name]) {
      clearAllPoints(dataSource[node.name]);
      delete dataSource[node.name];
      return;
    }

    // 如果是选中状态，添加点位
    if (checked) {
      try {
        dataSource[node.name] = node.data
          .map((point) => {
            if (!point.monitorType && !point.cameraType) {
              console.warn(`点位 ${point.name || '未知'} 缺少有效的monitorType或cameraType`);
              return null;
            }
            return addPoint(point, point.cameraType ? ComponentTitles.REAL_TIME_MONITORING : MonitorTypeLabelMap[point.monitorType]);
          })
          .filter(Boolean); // 过滤掉无效的点位
      } catch (error) {
        console.error('添加点位时发生错误:', error);
        Message.error('添加点位失败');
      }
    }
  };
  const initClearPoints = () => {
    Object.keys(dataSource).forEach((key) => {
      clearAllPoints(dataSource[key]);
      delete dataSource[key];
    });
    treeRef.value.setCheckedKeys([]);
  };
  //清楚全部点位得时候也需要清除点位的弹窗
  const clearPointDialog = () => {
    const popup = document.querySelector('.popup');
    if (popup) {
      popup.remove();
    }
  };
  return {
    retract,
    layerShow,
    svgList,
    treeData,
    treeRef,
    searchFlag,
    getList,
    atlasChange,
    screenChange,
    handleNodeClick,
    updateSvgUrl,
    initClearPoints
  };
});
